package com.example.demo01.Service.mobileService;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URISyntaxException;

@RestController
public class WeatherService {


    @RequestMapping(value = "/weather/GET/threeday")
    public String getCityId(
            @RequestParam(value = "lon") String lon,
            @RequestParam(value = "lat") String lat
    ){
        String locationInfo=lon+","+lat;
        String baseInfo=getHttpGetResultBody("https://geoapi.qweather.com/v2/city/lookup",locationInfo);//"113.252217,35.187198"
        System.out.println(baseInfo);
        //获取城市信息
        String cityId=getCityIdOfResult(baseInfo,"id");
        String city=getCityIdOfResult(baseInfo,"country")+","+getCityIdOfResult(baseInfo,"adm1");//城市名称
        String domain=getCityIdOfResult(baseInfo,"name");//曲线名称
        String weatherInfo=getHttpGetResultBody("https://devapi.qweather.com/v7/weather/3d",cityId);
        JSONObject daily=JSONObject.parseObject(weatherInfo);
        //获取详细信息
        JSONArray jsonArray = JSONArray.parseArray(daily.get("daily").toString());
        String result="{city:\""+city+"\",domain:\""+domain+"\",res:"+jsonArray.toJSONString()+"}";
        return JSONObject.parseObject(result).toJSONString();
    }

    /**
     * 获取查询结果
     * @param baseurl
     * @param location
     * @return
     */
    public String getHttpGetResultBody(String baseurl,String location){
        CloseableHttpClient httpClient=null;//请求体
        CloseableHttpResponse httpResponse=null;//响应体
        HttpGet httpGet=null;//get请求
        URIBuilder uriBuilder=null;//网络资源请求路径
        String resInfo="";
        //业务逻辑
        try {
            //实例化资源路径
            uriBuilder=new URIBuilder(baseurl);//"https://geoapi.qweather.com/v2/city/lookup"
            //设置参数
            uriBuilder.setParameter("location",location);//"113.252217,35.187198"
            uriBuilder.setParameter("key","589d699389904131a904dab25872c6a9");
            //实例化请求体
            httpClient= HttpClients.createDefault();
            //实例化get请求
            httpGet=new HttpGet(uriBuilder.build());
            //设置请求头，模拟浏览器发起请求，避免拦截
            httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:0.9.4)");
            //发起get请求
            httpResponse = httpClient.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode()==200){
                resInfo = EntityUtils.toString(httpResponse.getEntity(), "utf8");
                System.out.println(resInfo);
//                String id=getCityIdOfResult(resInfo);
//                //根据id值获取天气信息 101181111
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭连接资源
            //释放连接资源
            if (httpResponse!=null)
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (httpClient!=null)
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return resInfo;
    }

    /***
     * 获取城市id值
     * @param resultStr
     * @return
     */
    public String getCityIdOfResult(String resultStr,String attr){
//        String str="{\"code\":\"200\",\"location\":[{\"name\":\"山阳\",\"id\":\"101181111\",\"lat\":\"35.21475983\",\"lon\":\"113.26766205\",\"adm2\":\"焦作\",\"adm1\":\"河南省\",\"country\":\"中国\",\"tz\":\"Asia/Shanghai\",\"utcOffset\":\"+08:00\",\"isDst\":\"0\",\"type\":\"city\",\"rank\":\"35\",\"fxLink\":\"http://hfx.link/1ttq1\"}],\"refer\":{\"sources\":[\"qweather.com\"],\"license\":[\"commercial license\"]}}";
        JSONObject resultSet = JSONObject.parseObject(resultStr);
        //获取cityid
        JSONArray location = JSONArray.parseArray(resultSet.get("location").toString());
        //解析第一条记录
        JSONObject element = JSONObject.parseObject(location.get(0).toString());
        String id=element.get(attr).toString();//默认为id
        return id;
    }


    @Test
    public void test2(){
        String baseInfo=getHttpGetResultBody("https://geoapi.qweather.com/v2/city/lookup","113.252217,35.187198");
        String cityId=getCityIdOfResult(baseInfo,"id");
        String weatherInfo=getHttpGetResultBody("https://devapi.qweather.com/v7/weather/3d",cityId);
        JSONObject daily=JSONObject.parseObject(weatherInfo);
        //获取详细信息
        JSONArray jsonArray = JSONArray.parseArray(daily.get("daily").toString());
        System.out.println(jsonArray.toJSONString());
    }


    @Test
    public void test1(){
       //?=&=
        CloseableHttpClient httpClient=null;//请求体
        CloseableHttpResponse httpResponse=null;//响应体
        HttpGet httpGet=null;//get请求
        URIBuilder uriBuilder=null;//网络资源请求路径
        String resInfo="";
        //业务逻辑
        try {
            //实例化资源路径
            uriBuilder=new URIBuilder("https://geoapi.qweather.com/v2/city/lookup");
            //设置参数
            uriBuilder.setParameter("location","113.252217,35.187198");
            uriBuilder.setParameter("key","589d699389904131a904dab25872c6a9");
            //实例化请求体
            httpClient= HttpClients.createDefault();
            //实例化get请求
            httpGet=new HttpGet(uriBuilder.build());
            //设置请求头，模拟浏览器发起请求，避免拦截
            httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:0.9.4)");
            //发起get请求
            httpResponse = httpClient.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode()==200){
                resInfo = EntityUtils.toString(httpResponse.getEntity(), "utf8");

                String id=getCityIdOfResult(resInfo,"id");
               //根据id值获取天气信息 101181111

                System.out.println(resInfo);
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭连接资源
            //释放连接资源
            if (httpResponse!=null)
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (httpClient!=null)
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }



}
